#encoding:utf8
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from web.forms import MonitorImage
from datetime import *
import sys,commands,time
sys.path.append('/cihi/app/include')
import init

k = init.INIT()
webdir = k.WorkDir_web

def image(request):     #详细的每个时间段的图
    host = request.GET.get('host')
    monitor = request.GET.get('monitor')
    if host and monitor:
        if request.method == 'POST':
            form = MonitorImage(request.POST)
            if form.is_valid():
                result = form.cleaned_data
                starttime = time.mktime(result['starttime'].timetuple())
                endtime = time.mktime(result['endtime'].timetuple())
                param = "\'%.0f --end %.0f\'" % (starttime,endtime) 
                status,output = commands.getstatusoutput('%s/rrdtool/rrdtoolimage -i %s -p %s -t %s' % (webdir,host,monitor,param))
        else:
                status,output = commands.getstatusoutput('%s/rrdtool/rrdtoolimage -i %s -p %s' % (webdir,host,monitor))
        if status != 0:
            errorinfo = 'Rrrdtool draw failed'
            errormsg = output
    else:
        errorinfo = 'Rrrdtool Missing param'
    form = MonitorImage(initial={'starttime':datetime.now(),'endtime':datetime.now()},label_suffix='')
    return render_to_response('images/image.html',locals())

def monitor(request):   #所有主机的某个监控项的图
    monitor = request.GET.get('monitor')
    if monitor:
        hostlist = k.getMonitorHavClient(monitor)
        errormsg = ''
        for host in hostlist:
            status,output = commands.getstatusoutput('%s/rrdtool/rrdtoolimage -i %s -p %s -t 1d' % (webdir,host,monitor))
            if status != 0:
                errorinfo = 'Rrrdtool dram failed for %s %s' % (host,monitor)
                errormsg += output 
    else:
        errorinfo = 'Rrrdtool Missing param'
    return render_to_response('images/monitor.html',locals())

def host(request):    #某个主机的所有监控项的图
    host = request.GET.get('host')
    imgmonitor = ['check_traffic','check_load','check_mem','check_disk','check_procs','check_ping','check_openfiles','check_tcpconnect']
    if host:
        monitorlist = k.getClientHavMonitor(host)
        errormsg = ''
        realmonitorlist = [ val for val in monitorlist if val in imgmonitor ] 
        for monitor in realmonitorlist:
            status,output = commands.getstatusoutput('%s/rrdtool/rrdtoolimage -i %s -p %s -t 1d' % (webdir,host,monitor))
            if status != 0:
                errorinfo = 'Rrrdtool dram failed for %s %s' % (host,monitor)
                errormsg += output 
    else:
        errorinfo = 'Rrrdtool Missing param'
    return render_to_response('images/host.html',locals())
